import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {Http} from "@angular/http";
import {ActivatedRoute} from "@angular/router";
import {MaintenanceService} from "../../shared/service/maintenance.service";

@Component({
  selector: 'app-maintenance-add-form',
  templateUrl: './maintenance-add-form.component.html',
  styleUrls: ['./maintenance-add-form.component.css']
})
export class MaintenanceAddFormComponent implements OnInit {
  userId: string = this.routeInfo.snapshot.queryParams['userId'];
  typeForm: FormGroup;
  IDValidFlag:boolean = false;
  constructor(private fb: FormBuilder,
              private http: Http,
              private routeInfo: ActivatedRoute,
              private maintenanceService:MaintenanceService) { }

  ngOnInit() {
    this.typeForm = this.fb.group({
      id: '', name: '', description: ''
    });
  }

  onSubmit(val:any){
    if(!this.IDValidFlag&&this.typeForm.get("id").value){
      return false;
    }else{
      let msg ="";
      if(!this.typeForm.get("id").value.replace(/^\s+|\s+$/g,"")){
        msg +=("请输入类型代号\n");
      }
      if(!this.typeForm.get("name").value.replace(/^\s+|\s+$/g,"")){
        msg +=("请输入类型名称\n");
      }

      if(msg){
        alert(msg);
      }else{
        this.maintenanceService.createMaintenanceType(this.typeForm.value).then(res => {
          //状态码1为成功
          if(res.code ===1){
            alert(res.message);
            this.maintenanceService.listFreshEvent.emit("add");
            this.typeForm.reset();
          }else{
            alert(res.message);
          }
        })
      }
    }

  }

  toSearchId(){
    let pid = this.typeForm.get('id').value;
    this.maintenanceService.checkMaintenanceTypeId(pid)
      .then(res => {
        if(res.code===1){
          alert("类型代号已存在，请重新输入！");
          this.typeForm.patchValue({
            id:'',
          });
          this.IDValidFlag = false;
        }else {
          this.IDValidFlag = true;
        }
      });
  }

}
